package com.qf.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.qf.pojo.Result;
import com.qf.service.BusinessService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@RestController
@RequestMapping("/report")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    @GetMapping
    public Result getBusinessData() throws InterruptedException {
        Map<String, Object> data = businessService.getData();

        return Result.success(data);
    }
    /**
     * 导出excel报表
     */
    @GetMapping("/exportPdf")
    public void exportPDF(HttpServletRequest req,HttpServletResponse resp) throws InterruptedException, IOException, JRException {
        //1、获取数据库中的运营数据
        Map<String, Object> data = businessService.getData();
        //设置日期
        data.put("reportDate",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        //模拟热门套餐数据
        Map map1 = new HashMap();
        map1.put("name","入职体检套餐");
        map1.put("setmeal_count","2000");
        map1.put("proportion","30%");

        Map map2 = new HashMap();
        map2.put("name","入职体检套餐2222");
        map2.put("setmeal_count","1000");
        map2.put("proportion","10%");

        List list = new ArrayList();
        list.add(map1);
        list.add(map2);

        //2、将数据填充到pdf文件  （itext -- jasper）
        //2.1、利用编译对象，对jrxml文件进行编译，得到jasper文件
        String templatePath = "C:\\Users\\aming\\Desktop\\uploads\\template\\health_business3.jrxml";
        String jasperDestPath = "C:\\Users\\aming\\Desktop\\uploads\\template\\health_business3.jasper";
        JasperCompileManager.compileReportToFile(templatePath,jasperDestPath);

        //2.2、将数据填充到jasper文件中
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperDestPath, data, new JRBeanCollectionDataSource(list));

        //2.3、将填充后的jasper按照要求导出对应格式
        String pdfPath = "C:\\Users\\aming\\Desktop\\uploads\\reports\\abc.pdf";
        JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);

        //3、将文件下载到浏览器端
        //两个头一个流
        //3.1、设置content-type头，指定要向浏览器端写出的文件类型
        String fileName = "abc.pdf";
        String mimeType = req.getServletContext().getMimeType(fileName);
        resp.setHeader("content-type",mimeType);
        //3.2、设置content-disposition头，告诉浏览器不要打开，以附件形式下载
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        //3.3、将要下载的文集以字节流的形式写出到浏览器端
        FileInputStream fis = new FileInputStream(pdfPath);
        ServletOutputStream os = resp.getOutputStream();

        int len = -1;
        byte[] bys = new byte[1024];
        while ((len=fis.read(bys)) != -1){
            os.write(bys,0,len);
        }

        //3.4、释放资源
        fis.close();
    }

    /**
     * 导出excel报表
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest req,HttpServletResponse resp) throws InterruptedException, IOException {
        //1、获取数据库中的运营数据
        Map<String, Object> data = businessService.getData();
        //设置当前日期
        data.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        //模拟热门套餐数据
        Map map1 = new HashMap();
        map1.put("setmealname","入职体检套餐");
        map1.put("setmealcount","2000");
        map1.put("percent","30%");

        Map map2 = new HashMap();
        map2.put("setmealname","入职体检套餐2222");
        map2.put("setmealcount","1000");
        map2.put("percent","10%");

        List list = new ArrayList();
        list.add(map1);
        list.add(map2);

        //2、将得到的数据写出到excel文件中
        String dirPath = "C:\\Users\\aming\\Desktop\\uploads\\reports";
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + ".xlsx";
        //写出的excel目标文件
        File destFile = new File(dirPath,fileName);

        //2.1获取excel写出构建器
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(destFile).withTemplate("C:\\Users\\aming\\Desktop\\uploads\\template\\report_template.xlsx");
        //2.1.1根据excel写出构建器获取sheet
        WriteSheet sheet = excelWriterBuilder.sheet().build();
        //2.1.2根据excel写出构建器获取一个写出对象
        ExcelWriter excelWriter = excelWriterBuilder.build();

        //2.2、利用excel写出对象，将数据填充到指定的sheet中
        excelWriter.fill(data,sheet);
        excelWriter.fill(list,sheet);

        //2.3、关闭资源
        excelWriter.finish();

        //3、将写出的excel文件下载到浏览器端(文件下载)
        //两个头一个流
        //3.1、设置content-type头，指定要向浏览器端写出的文件类型
        String mimeType = req.getServletContext().getMimeType(fileName);
        resp.setHeader("content-type",mimeType);
        //3.2、设置content-disposition头，告诉浏览器不要打开，以附件形式下载
        resp.setHeader("content-disposition","attachment;filename=" + fileName);

        //3.3、将要下载的文集以字节流的形式写出到浏览器端
        FileInputStream fis = new FileInputStream(destFile);
        ServletOutputStream os = resp.getOutputStream();

        int len = -1;
        byte[] bys = new byte[1024];
        while ((len=fis.read(bys)) != -1){
            os.write(bys,0,len);
        }

        //3.4、释放资源
        fis.close();
    }
}
